import { truthy } from '@gnlab/utils'
import { Steps } from 'antd'
import { EditModal } from '@/desktop/components'
import Loading from '@/desktop/components/Loading'
import { useQywxsForChoose, type QywxForChooseExtra } from '@/desktop/logics/config-choosing-qywxs'
import services from '@/services'
import type {
  BaseMonitorConfig,
  MonitorConfig,
  MonitorConfigQywx,
} from '@/services/features/group-monitor-apply'
import { getEmptyMonitorConfig } from '@/services/features/group-monitor-apply'
import ChooseQywxs from './ChooseQywxs'
import EditConfig from './EditConfig'
import './index.module.less'

export interface EditingConfig extends BaseMonitorConfig {
  id?: number
}

export type EditingQywx = MonitorConfigQywx & QywxForChooseExtra

export default function TaskDetailModal(props: {
  editing?: false | true | MonitorConfig
  onFinish: () => void
}) {
  const { editing, onFinish } = props

  const title = truthy(editing) ? (editing === true ? '新建群监控加人' : '编辑群监控加人') : ''

  return <EditModal
    title={title}
    footer={null}
    width="800px"
    open={truthy(editing)}
    onCancel={onFinish}
    maskClosable={false}
    destroyOnClose
  >
    {truthy(editing) ? <Content editing={editing} onFinish={onFinish} /> : null}
  </EditModal>
}

function Content(props: { editing: true | MonitorConfig; onFinish: () => void }) {
  const { editing, onFinish } = props

  const [choosingQywxs, setChoosingQywxs] = useState(true)
  const [config, setConfig] = useState<EditingConfig>(() =>
    editing === true ? getEmptyMonitorConfig() : editing,
  )

  const qywxs = useQywxsForChoose(
    editing === true ? null : editing.id,
    async (configId?: number) => services.features.groupMonitorApply.getQywxListForConfig(configId),
    qywx => qywx.configId,
  )

  const choosedQywxs = useCallback(
    (wxids: string[]) => {
      setConfig({ ...config, wxids })
      setChoosingQywxs(false)
    },
    [config],
  )

  const rechooseQywxs = useCallback((editedConfig: EditingConfig) => {
    setConfig(editedConfig)
    setChoosingQywxs(true)
  }, [])

  return <main>
    <div styleName="steps-wrap">
      <Steps current={choosingQywxs ? 0 : 1}>
        <Steps.Step title="选择企微账号" />
        <Steps.Step title="加人设置" />
      </Steps>
    </div>

    {qywxs ? (
      choosingQywxs ? (
        <ChooseQywxs qywxs={qywxs} wxids={config.wxids} choosed={choosedQywxs} />
      ) : (
        <EditConfig config={config} goPrev={rechooseQywxs} onFinish={onFinish} />
      )
    ) : (
      <Loading />
    )}
  </main>
}
